package com.share.zabbix.method;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.share.zabbix.entity.ZabbixTemplate;
import com.share.zabbix.request.ZabbixRequest;
import com.share.zabbix.request.ZabbixRequestBuilder;

import cn.hutool.core.util.StrUtil;

public class ZabbixTemplateMethod extends ZabbixBaseMethod{
	/**
	 * zabbix获取主机模板
	 * 
	 * @return
	 */
	public static List<ZabbixTemplate> getTemplates(String name) {
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder()
				.method("template.get")
				.paramEntry("selectTriggers", Arrays.asList("triggerid","description"))
				.paramEntry("selectItems", Arrays.asList("itemid", "name", "desc"))
				.build();
		if(!StrUtil.isEmpty(name)) {
			JSONObject filter = new JSONObject();
			filter.put("name", name);
			request.putFilter(filter);
		}
		JSONObject response = call(request);
		String result = response.getJSONArray(ZABBIX_KEY_RESULT).toJSONString();
		Gson gson = new GsonBuilder().create();
		List<ZabbixTemplate> templateList = gson.fromJson(result,
				new TypeToken<ArrayList<ZabbixTemplate>>() {
				}.getType());
		return templateList;
	}
	
	/**
	 * zabbix主机添加模板
	 * 
	 * @return
	 */
	public static void addTemplate(List<String> templateids, List<String> hostids) {
		JSONArray tarr = new JSONArray();
		JSONArray harr = new JSONArray();
		for(String tid : templateids) {
			JSONObject obj = new JSONObject();
			obj.put("templateid", tid);
			tarr.add(obj);
		}
		for(String hid : hostids) {
			JSONObject obj = new JSONObject();
			obj.put("hostid", hid);
			harr.add(obj);
		}
		ZabbixRequest request = ZabbixRequestBuilder.newBuilder()
				.method("template.massadd")
				.paramEntry("templates", tarr)
				.paramEntry("hostid", harr)
				.build();

		JSONObject response = call(request);
		String result = response.getJSONArray(ZABBIX_KEY_RESULT).toJSONString();
		log.info("addTemplate result:{}", result);
	}
	
}
